package com.cy.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.cy.common.vo.JsonResult;
import com.cy.entity.SysUser;
import com.cy.service.SysUserService;



@RestController
@RequestMapping("/user/")
public class SysUserController {

	@Autowired
	private SysUserService sysUserService;
		
	@RequestMapping("doGetUsername")
	public JsonResult doGetUsername(HttpServletRequest request) {
		HttpSession hs = request.getSession();
		String username = (String) hs.getAttribute("username");
		int id = (Integer)hs.getAttribute("id");
		SysUser user = new SysUser();
		user.setId(id);
		user.setUsername(username);
		JsonResult jr = new JsonResult(username);
		jr.setData(user);
		return jr;
	}

	@RequestMapping("doReg")
	public JsonResult doSaveObject(
			SysUser entity) {
		sysUserService.saveObject(entity);
		return new JsonResult("save ok");
	}

	@RequestMapping("doLogin")
	@ResponseBody
	public JsonResult doLogin(String username,String password,HttpServletRequest request){
		//1.获取Subject对象
		Subject subject=SecurityUtils.getSubject();
		//2.通过Subject提交用户信息,交给shiro框架进行认证操作
		//2.1对用户进行封装
		UsernamePasswordToken token=
				new UsernamePasswordToken(
						username,//身份信息
						password);//凭证信息
		//2.2对用户信息进行身份认证
		subject.login(token);
		SysUser findUser = sysUserService.findUser(username);
		request.getSession().setAttribute("username", username);
		request.getSession().setAttribute("id",findUser.getId());
		return new JsonResult("login ok");
	}


}
